<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.04.06
 */

namespace App\Library\Clog;

class Log
{
    const LEVEL_ERROR     = 'error';
    const LEVEL_INFO      = 'info';
    const LEVEL_EMERGENCY = 'emergency';
    const LEVEL_EXCEPTION = 'exception';

    private static $logInstances = array();

    /**
     * info
     *
     * @param       $name
     * @param       $message
     * @param array $context
     *
     * @return mixed
     */
    public static function info($name, $message, $context = [])
    {
        $message = is_array($message) ? json_encode($message, JSON_UNESCAPED_UNICODE) : $message;

        return static::getInstances($name, static::LEVEL_INFO)->info($message, $context);
    }

    /**
     * error
     *
     * @param string $name
     * @param string $message
     * @param array $context
     *
     * @return mixed
     */
    public static function error($name, $message, $context = [])
    {
        $message = is_array($message) ? json_encode($message, JSON_UNESCAPED_UNICODE) : $message;

        return static::getInstances($name, static::LEVEL_ERROR)->error($message, $context);
    }

    /**
     * exception
     *
     * @param Exception|Error $e
     * @param string $name
     *
     * @return mixed
     */
    public static function exception($e, $name = 'error')
    {
        return static::getInstances($name, static::LEVEL_EXCEPTION)
            ->error('exception', [
                'file'    => $e->getFile(),
                'line'    => $e->getLine(),
                'message' => $e->getMessage()
            ]);
    }

    /**
     * Get a singleton
     *
     * @param $name
     * @param $level
     *
     * @return mixed
     */
    public static function getInstances($name, $level)
    {
        $key = $name . $level;
        if (!empty(static::$logInstances[$key])) {
            return static::$logInstances[$key];
        }
        $logObj = new Logger($name);
        return static::$logInstances[$key] = $logObj;
    }

}
